//------------------------------------------------------------------------------
// File:          flash.h
// Function:      Flash function definitions
// Supported chip(s):
//    - SAM3X8
//    - SAM3X4
//    - SAM3X2
// Supported toolchain(s):
//    - IAR Embedded Workbench
//------------------------------------------------------------------------------

#ifndef BOOTLOADER_FLASH_H
#define BOOTLOADER_FLASH_H

//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------

//#include "board.h"
#include "compiler.h"

#define USE_FLASH

#ifdef USE_FLASH

//------------------------------------------------------------------------------
// Definitions
//------------------------------------------------------------------------------

// Functions
#define memory_init            flash_init
#define memory_cleanup         flash_cleanup
#define memory_write           flash_write
#define memory_next            flash_next
#define memory_lock            flash_lock
#define memory_unlock          flash_unlock

#define FLASH_TEST_ADDRESS     ((void *) 0x00125000)
#ifndef MEMORY_START_ADDRESS
#define MEMORY_START_ADDRESS   ((void *)IFLASH0_ADDR) /* Start from flash0 */
#endif
#ifndef MEMORY_START_ADDRESS0
#define MEMORY_START_ADDRESS0  ((void *)IFLASH0_ADDR) /* Start from flash0 */
#endif
#ifndef MEMORY_START_ADDRESS1
#define MEMORY_START_ADDRESS1  ((void *)IFLASH1_ADDR) /* Start from flash0 */
#endif
#ifndef MEMORY_SIZE
#define MEMORY_SIZE            (IFLASH_SIZE)  /* Whole flash */
#endif
#define MEMORY_PAGE_SIZE       (IFLASH_PAGE_SIZE)
#define MEMORY_PAGE_SIZE_32    (MEMORY_PAGE_SIZE / 4)

// Region size in pages
#define MEMORY_REGION_SIZE     64
#define MEMORY_REGION_MASK     0xFFFFFFC0

#define IFLASH0_END            (IFLASH0_ADDR+IFLASH0_SIZE-1)
#define IFLASH1_END            (IFLASH1_ADDR+IFLASH1_SIZE-1)
#define IFLASH_END             (IFLASH0_ADDR+IFLASH_SIZE-1)

// Errors (unsigned ints)
#define OK          0x00000000
#define ERROR       0xFFFFFFFF

/// Cortex-M3 SRAM region end
#define CM3_SRAM_END        0x3FFFFF80

//------------------------------------------------------------------------------
// Prototypes
//------------------------------------------------------------------------------

void flash_init(void);
void flash_cleanup(void);
unsigned int flash_write(void *, void *);
//void flash_read(void *vAddress,uint8_t *buf);
//uint32_t flash_compare(void *vAddress,uint8_t *buf);
void * flash_next(void *);
unsigned int flash_lock(void *, void *);
unsigned int flash_unlock(void *, void *);
void _binExec (void * l_code_addr);
int binary_exec(void * vStart);

#endif // USE_FLASH
#endif // BOOTLOADER_FLASH_H
